package com.ruoyi.quartz.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.domain.AttendanceRecord;
import com.ruoyi.common.domain.Emply;
import com.ruoyi.common.domain.Holidays;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.*;
import com.ruoyi.quartz.util.HolidayUtil;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;

/**
 * 定时任务调度信息 服务层
 * 
 * @author ruoyi
 */
@Service
public class SysJobServiceImpl implements ISysJobService
{
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper jobMapper;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     * 
     * @param job 调度信息
     * @return
     */
    @Override
    public List<SysJob> selectJobList(SysJob job)
    {
        return jobMapper.selectJobList(job);
    }

    /**
     * 通过调度任务ID查询调度信息
     * 
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(Long jobId)
    {
        return jobMapper.selectJobById(jobId);
    }

    /**
     * 暂停任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteJobById(jobId);
        if (rows > 0)
        {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     * 
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException
    {
        for (Long jobId : jobIds)
        {
            SysJob job = jobMapper.selectJobById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException
    {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
        {
            rows = resumeJob(job);
        }
        else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
        {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
    }

    /**
     * 新增任务
     * 
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException
    {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws SchedulerException, TaskException
    {
        SysJob properties = selectJobById(job.getJobId());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 更新任务
     * 
     * @param job 任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
    {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     * 
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression)
    {
        return CronUtils.isValid(cronExpression);
    }


    @Override
    @DataSource(DataSourceType.MASTER)
    public Holidays getHolidays(String date){
        return jobMapper.selectHolidays(date);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<AttendanceRecord>  getToDayAttendanceInfo(String date){
        String startTime = date.toString() + " 00:00:00";
        String endTime = date.toString() + " 23:59:59";
        return jobMapper.getToDayAttendanceInfo(startTime, endTime);
    }

    @Override
    public List<Holidays> getHolidaysByDate(String startDate, String endDate) {
        return this.jobMapper.getHolidaysByDate(startDate, endDate);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<Emply> getEmplyList(){
        return jobMapper.getEmplyList();
    }


    @Override
    public void dealAttendanceInfo(String date, Holidays holidays, List<AttendanceRecord> attendAnceInfoList, List<Emply> emplyList) {

        //if(holidays.getType() == 0){


            List<AttendanceStatistics> attendanceStatisticsList = new Vector<>();


            if(attendAnceInfoList != null && attendAnceInfoList.size() > 0){

                //所有人员考勤
                Map<String, List<AttendanceRecord>> deptGroupInfo = attendAnceInfoList.stream().collect(Collectors.groupingBy(AttendanceRecord::getSysNo));
                //所有人员
                Map<String, List<Emply>> groupEmplyList = emplyList.stream().collect(Collectors.groupingBy(Emply::getSysNo));

                //根据所有人员遍历
                for (Map.Entry<String, List<Emply>> map : groupEmplyList.entrySet()) {

                    List<AttendanceRecord> attendanceRecords = deptGroupInfo.get(map.getKey());
//                    Map<String, List<AttendanceRecord>> attendanceRecordMap = new HashMap<>();
                    try {
                        if(attendanceRecords != null && attendanceRecords.size() > 0){
//                            attendanceRecordMap = attendanceRecordList.stream().sorted(Comparator.comparing(AttendanceRecord::getCardTime)).collect(Collectors.groupingBy(AttendanceRecord::getSysNo));
                            attendanceRecords = attendanceRecords.stream().sorted(Comparator.comparing(AttendanceRecord::getCardTime)).collect(Collectors.toList());
                        }
                        for (Emply p: map.getValue()) {
//                            List<AttendanceRecord> attendanceRecords = attendanceRecordMap.get(p.getSysNo());
                            AttendanceStatistics statistics = new AttendanceStatistics();
                            statistics.setSysNo(p.getSysNo());
                            statistics.setDeptId(p.getDepartId());//部门ID
                            statistics.setDeptName(p.getDepartName());//部门名称
                            statistics.setEmployeeId(p.getEmployeeId());//员工ID
                            statistics.setEmpName(p.getEmployeeName());//员工姓名
                            statistics.setCalDate(DateUtils.parseDate(date));//打卡日期
                            statistics.setCalDateText(date);
                            if(attendanceRecords != null && attendanceRecords.size() > 0){
                                AttendanceRecord first = attendanceRecords.get(0);
                                AttendanceRecord end = null;
                                if(attendanceRecords.size() > 1){
                                    end = attendanceRecords.get(attendanceRecords.size() - 1);
                                    statistics.setDrawtmbgn(first.getCardTime());//上班打卡时间
                                    statistics.setDrawtmend(end.getCardTime());//下班打卡时间
                                    statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                    statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, end.getCardTime()));
                                } else {

                                    statistics.setStatus(2);//异常
                                    statistics.setStatusText("异常");
                                    end = first;
                                    //判断未签入/未签出
                                    if(judegStatus(first.getCardTime())){
                                        statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                        statistics.setDrawtmendText("未签出");
                                    } else {
                                        statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                        statistics.setDrawtmbgnText("未签入");
                                    }
                                }
                                long min = DateUtils.getMin(end.getCardTime(), first.getCardTime());
                                statistics.setFactGs((int)min);

                                if(judegDate(first.getCardTime(), end.getCardTime()) && min >= 510){
                                    statistics.setStatus(1);
                                    statistics.setStatusText("正常");
                                } else {
                                    statistics.setStatus(2);
                                    statistics.setStatusText("异常");
                                }
                            } else {
                                statistics.setDrawtmendText("未签出");
                                statistics.setDrawtmbgnText("未签入");
                                statistics.setStatus(2);
                                statistics.setStatusText("异常");
                                statistics.setFactGs(0);
                            }
                            statistics.setIsWeekend(holidays.getType() == 0 ? "否" : "是");
                            if(holidays.getType() == 0){
                                statistics.setRemark("工作日");
                            }
                            if(holidays.getType() == 1){
                                statistics.setRemark("周末");
                            }
                            if(holidays.getType() == 2){
                                statistics.setRemark("节假日");
                            }
                            attendanceStatisticsList.add(statistics);
                        };

                        System.out.println("共" + attendanceStatisticsList.size() + "条数据");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                insertAttendanceStatisticsList(date, attendanceStatisticsList);

            }
        //}
    }

    @Override
    @DataSource(DataSourceType.MASTER)
    public List<AttendanceStatistics> selectByDate(String date){
        return jobMapper.selectByDate(date);
    }

    @Override
    @DataSource(DataSourceType.MASTER)
    public void insertAttendanceStatisticsList(String date, List<AttendanceStatistics> attendanceStatisticsList){
        List<AttendanceStatistics> list = selectByDate(date);
        if(StringUtils.isEmpty(list)){
//                            Thread.sleep(3000);
            jobMapper.insertAttendanceStatisticsList(attendanceStatisticsList);
        }
    }

    @Override
    @DataSource(DataSourceType.MASTER)
    public void genHolidays(String params) {
        List<Holidays> holidays = HolidayUtil.genHolidaysDate(Integer.valueOf(params));
        jobMapper.insertHolidays(holidays);
    }


    public boolean judegDate(Date startDate, Date endDate){
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startDate);
        Date startWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 09:00:59");
        Date endWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 17:00:00");
        if(startDate.getTime() <= startWorkDate.getTime() && endDate.getTime() >= endWorkDate.getTime()){
            return true;
        } else {
            return false;
        }
    }

    public boolean judegStatus(Date startDate){
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startDate);
        Date endWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 17:00:00");

        if(startDate.getTime() < endWorkDate.getTime()){
            return true;
        } else {
            return false;
        }
    }

        /*if(attendAnceInfoList != null && attendAnceInfoList.size() > 0){
        List<AttendanceStatistics> statisticsList = new Vector<>();

        Map<Integer, List<AttendanceRecord>> deptGroupInfo = attendAnceInfoList.stream().collect(Collectors.groupingBy(AttendanceRecord::getDeptId));
        Map<Integer, List<Emply>> groupEmplyList = emplyList.stream().collect(Collectors.groupingBy(Emply::getDepartId));

    //                CyclicBarrier barrier = new CyclicBarrier(deptGroupInfo.size(),new TotalTask(statisticsList, jobMapper, date));
        for (Map.Entry<Integer, List<Emply>> map : groupEmplyList.entrySet()) {
    //                    new GroupTask(barrier, deptGroupInfo.get(map.getKey()), statisticsList, date, map.getValue()).start();
            List<AttendanceRecord> attendanceRecordList = deptGroupInfo.get(map.getKey());
            Map<String, List<AttendanceRecord>> attendanceRecordMap = new HashMap<>();
            try {
                if(attendanceRecordList != null && attendanceRecordList.size() > 0){
                    attendanceRecordMap = attendanceRecordList.stream().sorted(Comparator.comparing(AttendanceRecord::getCardTime)).collect(Collectors.groupingBy(AttendanceRecord::getSysNo));
                }
                for (Emply p: map.getValue()) {
                    List<AttendanceRecord> attendanceRecords = attendanceRecordMap.get(p.getSysNo());
                    AttendanceStatistics statistics = new AttendanceStatistics();
                    statistics.setSysNo(p.getSysNo());
                    statistics.setDeptId(p.getDepartId());//部门ID
                    statistics.setDeptName(p.getDepartName());//部门名称
                    statistics.setEmployeeId(p.getEmployeeId());//员工ID
                    statistics.setEmpName(p.getEmployeeName());//员工姓名
                    statistics.setCalDate(DateUtils.parseDate(date));//打卡日期
                    statistics.setCalDateText(date);
                    if(attendanceRecords != null && attendanceRecords.size() > 0){
                        AttendanceRecord first = attendanceRecords.get(0);
                        AttendanceRecord end = null;
                        if(attendanceRecords.size() > 1){
                            end = attendanceRecords.get(attendanceRecords.size() - 1);
                            statistics.setDrawtmbgn(first.getCardTime());//上班打卡时间
                            statistics.setDrawtmend(end.getCardTime());//下班打卡时间
                            statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                            statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, end.getCardTime()));
                        } else {

                            statistics.setStatus(2);//异常
                            statistics.setStatusText("异常");
                            end = first;
                            //判断未签入/未签出
                            if(judegStatus(first.getCardTime())){
                                statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                statistics.setDrawtmendText("未签出");
                            } else {
                                statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                statistics.setDrawtmbgnText("未签入");
                            }
                        }
                        long min = DateUtils.getMin(end.getCardTime(), first.getCardTime());
                        statistics.setFactGs((int)min);

                        if(judegDate(first.getCardTime(), end.getCardTime()) && min >= 510){
                            statistics.setStatus(1);
                            statistics.setStatusText("正常");
                        } else {
                            statistics.setStatus(2);
                            statistics.setStatusText("异常");
                        }
                    } else {
                        statistics.setDrawtmendText("未签出");
                        statistics.setDrawtmbgnText("未签入");
                        statistics.setStatus(2);
                        statistics.setStatusText("异常");
                        statistics.setFactGs(0);
                    }
                    statistics.setIsWeekend(holidays.getType() == 0 ? "是" : "否");
                    if(holidays.getType() == 0){
                        statistics.setRemark("工作日");
                    }
                    if(holidays.getType() == 1){
                        statistics.setRemark("周末");
                    }
                    if(holidays.getType() == 2){
                        statistics.setRemark("节假日");
                    }
                    attendanceStatisticsList.add(statistics);
                };

                System.out.println("共" + attendanceStatisticsList.size() + "条数据");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        insertAttendanceStatisticsList(date, attendanceStatisticsList);

    }*/
}
